#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
import os
import subprocess
from logger import logger


def _analysis_out(cmd_result, res_container: list):
    if not cmd_result:
        return
    for line in cmd_result.decode("utf-8", errors="ignore").split(os.linesep):
        line = line.strip()
        if line and line != os.linesep:
            logger.info(line)
            res_container.append(line)


def command(cmds: list, input=None, cwd=None):
    """
    Executing shell commands
    :param cmd_list: Command set
    :param cwd: Directory where the command is executed
    :returns: Result is a tuple,exp: (status code,output,err)
    """
    output, error = [], []
    try:
        pipe = subprocess.Popen(
            cmds,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            cwd=cwd,
        )
    except FileNotFoundError:
        cmds = " ".join(cmds)
        logger.error(f"Command not found:{cmds}.")
        error.append(f"Command not found:{cmds}.")
        return 1, output, error
    if input:
        pipe.stdin.write(input)

    _output, _error = pipe.communicate()
    logger.info(f"Return status code:{pipe.returncode}")
    if pipe.returncode:
        _analysis_out(_error, error)
    else:
        _analysis_out(_output, output)
    return pipe.returncode, output, error


__all__ = "command"
